package com.example.publishDemo.Controller;

import com.example.publishDemo.Model.AjaxResult;
import com.example.publishDemo.Model.Comment;
import com.example.publishDemo.Service.CommentService;
import org.springframework.web.bind.annotation.*;
import sun.util.resources.LocaleData;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@CrossOrigin
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Resource
    CommentService service;

    @GetMapping("/delComment")
    public AjaxResult delComment(@RequestParam int c_id, int r_id, int p_id) {
        service.delComment(c_id, r_id, p_id);
        return AjaxResult.success(true);
    }

    @PostMapping("/save")
    public AjaxResult save(@RequestBody Comment comment) {
        comment.setCreatetime(LocalDateTime.now());
        int save = service.save(comment);
        if(save > 0){
            return AjaxResult.success(true);
        }
        return AjaxResult.error("err",false);
    }

    @GetMapping("/articleComment")
    public AjaxResult articleComment(@RequestParam int a_id) {
        List<Comment> comments = service.articleComment(a_id);

        List<Comment> rootCollect = comments.stream().filter(comment -> comment.getP_id() == 0).collect(Collectors.toList());
//        List<Boolean> collect = comments.stream().map(comment -> comment.getP_id() == 0).collect(Collectors.toList());
////        collect.forEach(a-> System.out.println(a));
        for (Comment comment:
             rootCollect) {
            comment.setChildren(comments.stream().filter(childComment->comment.getC_id() == childComment.getP_id()).collect(Collectors.toList()));
        }

        return AjaxResult.success(rootCollect);
    }
}
